import React, { useState, useRef, useEffect } from 'react'
import { useResumeUpload } from '../../hooks/useResumeUpload'
import { UploadTask } from '../../utils/resumeUpload'
import styles from './index.module.css'

// 组件属性接口
export interface ResumeUploadProps {
  // 最大文件数量
  maxFiles?: number
  // 支持的文件类型
  accept?: string
  // 是否支持多选
  multiple?: boolean
  // 上传回调
  onUploadComplete?: (results: Array<{ success: boolean; url?: string; error?: string; fileName?: string }>) => void
  // 进度回调
  onProgress?: (fileIndex: number, task: UploadTask) => void
  // 是否显示任务列表
  showTaskList?: boolean
  // 是否显示未完成任务
  showUnfinishedTasks?: boolean
  // 自定义样式类名
  className?: string
}

// 文件项接口
interface FileItem {
  id: string
  file: File
  task?: UploadTask
  preview?: string
  status: 'pending' | 'uploading' | 'paused' | 'completed' | 'failed'
  progress: number
  error?: string
}

const ResumeUpload: React.FC<ResumeUploadProps> = ({
  maxFiles = 9,
  accept = 'image/*',
  multiple = true,
  onUploadComplete,
  onProgress,
  showTaskList = true,
  showUnfinishedTasks = true,
  className = ''
}) => {
  // 使用断点续传Hook
  const {
    isUploading,
    uploadProgress,
    uploadSpeed,
    remainingTime,
    currentTask,
    allTasks,
    unfinishedTasks,
    uploadFile,
    uploadMultipleFiles,
    pauseCurrentUpload,
    resumeCurrentUpload,
    cancelCurrentUpload,
    retryFailedUpload,
    clearCompleted,
    hasUnfinished,
    refreshTasks
  } = useResumeUpload({
    autoClearCompleted: true,
    checkUnfinishedOnMount: true,
    clearInterval: 30000
  })

  // 本地状态
  const [fileItems, setFileItems] = useState<FileItem[]>([])
  const [dragActive, setDragActive] = useState(false)
  const [showUnfinished, setShowUnfinished] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  // 格式化上传速度
  const formatSpeed = (bytesPerSecond: number): string => {
    return formatFileSize(bytesPerSecond) + '/s'
  }

  // 格式化剩余时间
  const formatTime = (seconds: number): string => {
    if (seconds < 60) {
      return `${Math.round(seconds)}秒`
    } else if (seconds < 3600) {
      return `${Math.round(seconds / 60)}分钟`
    } else {
      return `${Math.round(seconds / 3600)}小时`
    }
  }

  // 处理文件选择
  const handleFileSelect = async (files: FileList | null) => {
    if (!files || files.length === 0) return

    const fileArray = Array.from(files)
    const validFiles = fileArray.slice(0, maxFiles - fileItems.length)

    // 创建文件项
    const newFileItems: FileItem[] = validFiles.map(file => ({
      id: `file_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      file,
      status: 'pending',
      progress: 0,
      preview: file.type.startsWith('image/') ? URL.createObjectURL(file) : undefined
    }))

    setFileItems(prev => [...prev, ...newFileItems])

    // 开始上传
    for (let i = 0; i < newFileItems.length; i++) {
      const fileItem = newFileItems[i]
      const fileIndex = fileItems.length + i

      try {
        const result = await uploadFile(fileItem.file, (task) => {
          // 更新文件项状态
          setFileItems(prev => prev.map(item => 
            item.id === fileItem.id 
              ? { 
                  ...item, 
                  task, 
                  status: task.status as any, 
                  progress: task.progress,
                  error: task.error
                }
              : item
          ))

          // 调用外部进度回调
          if (onProgress) {
            onProgress(fileIndex, task)
          }
        })

        // 更新最终状态
        setFileItems(prev => prev.map(item => 
          item.id === fileItem.id 
            ? { 
                ...item, 
                status: result.success ? 'completed' : 'failed',
                error: result.error
              }
            : item
        ))

      } catch (error) {
        setFileItems(prev => prev.map(item => 
          item.id === fileItem.id 
            ? { 
                ...item, 
                status: 'failed',
                error: error instanceof Error ? error.message : '上传失败'
              }
            : item
        ))
      }
    }

    // 通知上传完成
    if (onUploadComplete) {
      const results = newFileItems.map(item => ({
        success: item.status === 'completed',
        url: item.task?.status === 'completed' ? 'uploaded_url' : undefined, // 这里需要从task获取实际URL
        error: item.error,
        fileName: item.file.name
      }))
      onUploadComplete(results)
    }
  }

  // 处理拖拽
  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
  }

  const handleDragIn = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setDragActive(true)
  }

  const handleDragOut = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setDragActive(false)
  }

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setDragActive(false)
    
    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      handleFileSelect(e.dataTransfer.files)
    }
  }

  // 处理文件输入变化
  const handleFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    handleFileSelect(e.target.files)
  }

  // 处理点击上传区域
  const handleUploadAreaClick = () => {
    fileInputRef.current?.click()
  }

  // 暂停上传
  const handlePause = async (fileItem: FileItem) => {
    if (fileItem.task) {
      await pauseCurrentUpload()
    }
  }

  // 恢复上传
  const handleResume = async (fileItem: FileItem) => {
    if (fileItem.task) {
      await resumeCurrentUpload(fileItem.file)
    }
  }

  // 取消上传
  const handleCancel = async (fileItem: FileItem) => {
    if (fileItem.task) {
      await cancelCurrentUpload()
    }
    setFileItems(prev => prev.filter(item => item.id !== fileItem.id))
  }

  // 重试上传
  const handleRetry = async (fileItem: FileItem) => {
    if (fileItem.task) {
      await retryFailedUpload(fileItem.task.id, fileItem.file)
    }
  }

  // 删除文件项
  const handleRemove = (fileItem: FileItem) => {
    if (fileItem.preview) {
      URL.revokeObjectURL(fileItem.preview)
    }
    setFileItems(prev => prev.filter(item => item.id !== fileItem.id))
  }

  // 清理已完成的任务
  const handleClearCompleted = () => {
    clearCompleted()
    setFileItems(prev => prev.filter(item => item.status !== 'completed'))
  }

  // 组件挂载时刷新任务
  useEffect(() => {
    refreshTasks()
  }, [refreshTasks])

  return (
    <div className={`${styles.container} ${className}`}>
      {/* 上传区域 */}
      <div
        className={`${styles.uploadArea} ${dragActive ? styles.dragActive : ''}`}
        onDragEnter={handleDragIn}
        onDragLeave={handleDragOut}
        onDragOver={handleDrag}
        onDrop={handleDrop}
        onClick={handleUploadAreaClick}
      >
        <input
          ref={fileInputRef}
          type="file"
          accept={accept}
          multiple={multiple}
          onChange={handleFileInputChange}
          style={{ display: 'none' }}
        />
        
        <div className={styles.uploadContent}>
          <div className={styles.uploadIcon}>📁</div>
          <div className={styles.uploadText}>
            {dragActive ? '松开鼠标上传文件' : '点击或拖拽文件到此处上传'}
          </div>
          <div className={styles.uploadHint}>
            支持断点续传，网络中断可自动恢复
          </div>
        </div>
      </div>

      {/* 文件列表 */}
      {fileItems.length > 0 && (
        <div className={styles.fileList}>
          {fileItems.map((fileItem) => (
            <div key={fileItem.id} className={styles.fileItem}>
              <div className={styles.fileInfo}>
                {fileItem.preview && (
                  <img src={fileItem.preview} alt="预览" className={styles.filePreview} />
                )}
                <div className={styles.fileDetails}>
                  <div className={styles.fileName}>{fileItem.file.name}</div>
                  <div className={styles.fileSize}>{formatFileSize(fileItem.file.size)}</div>
                  {fileItem.status === 'uploading' && (
                    <div className={styles.uploadStats}>
                      <div className={styles.progressBar}>
                        <div 
                          className={styles.progressFill} 
                          style={{ width: `${fileItem.progress}%` }}
                        />
                      </div>
                      <div className={styles.progressText}>
                        {fileItem.progress}% - {formatSpeed(uploadSpeed)} - 剩余{formatTime(remainingTime)}
                      </div>
                    </div>
                  )}
                  {fileItem.error && (
                    <div className={styles.errorText}>{fileItem.error}</div>
                  )}
                </div>
              </div>
              
              <div className={styles.fileActions}>
                {fileItem.status === 'uploading' && (
                  <button 
                    className={styles.actionButton}
                    onClick={() => handlePause(fileItem)}
                    title="暂停"
                  >
                    ⏸️
                  </button>
                )}
                {fileItem.status === 'paused' && (
                  <button 
                    className={styles.actionButton}
                    onClick={() => handleResume(fileItem)}
                    title="恢复"
                  >
                    ▶️
                  </button>
                )}
                {fileItem.status === 'failed' && (
                  <button 
                    className={styles.actionButton}
                    onClick={() => handleRetry(fileItem)}
                    title="重试"
                  >
                    🔄
                  </button>
                )}
                {(fileItem.status === 'uploading' || fileItem.status === 'paused') && (
                  <button 
                    className={styles.actionButton}
                    onClick={() => handleCancel(fileItem)}
                    title="取消"
                  >
                    ❌
                  </button>
                )}
                <button 
                  className={styles.actionButton}
                  onClick={() => handleRemove(fileItem)}
                  title="删除"
                >
                  🗑️
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* 任务管理 */}
      {showTaskList && (allTasks.length > 0 || hasUnfinished) && (
        <div className={styles.taskManagement}>
          <div className={styles.taskHeader}>
            <h3>上传任务</h3>
            <div className={styles.taskActions}>
              {allTasks.some(task => task.status === 'completed') && (
                <button 
                  className={styles.clearButton}
                  onClick={handleClearCompleted}
                >
                  清理已完成
                </button>
              )}
              <button 
                className={styles.refreshButton}
                onClick={refreshTasks}
              >
                刷新
              </button>
            </div>
          </div>
          
          {showUnfinishedTasks && unfinishedTasks.length > 0 && (
            <div className={styles.unfinishedTasks}>
              <h4>未完成任务 ({unfinishedTasks.length})</h4>
              {unfinishedTasks.map(task => (
                <div key={task.id} className={styles.taskItem}>
                  <div className={styles.taskInfo}>
                    <div className={styles.taskName}>{task.fileName}</div>
                    <div className={styles.taskProgress}>
                      {task.progress}% - {formatFileSize(task.fileSize)}
                    </div>
                  </div>
                  <div className={styles.taskStatus}>
                    {task.status === 'paused' ? '⏸️ 已暂停' : '❌ 失败'}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  )
}

export default ResumeUpload
